<template>
  <div class="login-container">
    <el-form ref="loginForm" :model="userForm" :rules="userRules" class="login-form">
      <h3 class="title">登录</h3>
      <el-form-item prop="username">
        <el-input
          v-model="userForm.username"
          placeholder="请输入用户名"
          clearable
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="userForm.password"
          placeholder="请输入密码"
          show-password
          clearable
          style="width: 100%"
        />
      </el-form-item>
      <div class="img-verify">
        <canvas
          ref="verify"
          width="120"
          height="40"
          @click="handleDraw"
        ></canvas>
      </div>
      <el-form-item prop="Code" class="Captcha">
        <el-input
          v-model="userForm.Code"
          style="width: 150px"
          placeholder="请输入验证码"
        ></el-input>
      </el-form-item>
      <el-form-item class="form-button">
        <el-button type="primary" style="width: 100%" @click="submitForm">登录</el-button>
      </el-form-item>
      <div class="enroll">
        <router-link to="/login/enroll">新用户注册</router-link>
      </div>
    </el-form>
  </div>
</template>

<script setup>
//导入useLogon Hook仓库
import { useLogon } from "./Hooks/useLogon"
//导入验证码仓库
import { Captcha } from "./Hooks/Captcha"
import { reactive, ref } from "vue"
//导入路由
import router from "@/router"

//从useLogon库中解构
const { userForm,loginForm,submitForm } = useLogon()

const { state, verify, handleDraw,draw } = Captcha()

//表单验证,验证码验证放在token中异步报错
const code = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输入验证码"))
  } else if (value !== state.imgCode) {
    callback(new Error("验证码错误"))
  } else {
    callback()
  }
}

const userRules = reactive({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  Code: [{ validator: code,trigger: "blur" }],
})
</script>

<style scoped>
.login-container {
  /* margin: auto; */
  margin-top: 80px;
  width: 400px;
  height: 200px;
}
.login-form {
  margin: auto 60px;
  position: relative;
}
.login-container .title {
  font-size: 26px;
  font-weight: 700;
  color: #fff;
  margin: 0px auto 40px auto;
  text-align: center;
  font-weight: bold;
}
/* .form-button{
  margin-top: 50px;
} */
.img-verify {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  /* background-color: #eee; */
  height: 34px;
}
.Captcha {
  position: absolute;
  top: 175px;
  left: 130px;
}
.enroll a{
  color: #f06868;
}
</style>
